package com.scproject.scbef.service.study.schoolnews.impl;

import com.scproject.dto.ResponseDto;
import com.scproject.scbef.exception.ProcessException;
import com.scproject.scbef.mapper.ImgMapper;
import com.scproject.scbef.mapper.ImgRelationMapper;
import com.scproject.scbef.mapper.SchoolNewsMapper;
import com.scproject.scbef.mapper.expandmapper.SchoolNewsInfoMapper;
import com.scproject.scbef.pojo.Img;
import com.scproject.scbef.pojo.ImgRelation;
import com.scproject.scbef.pojo.SchoolNews;
import com.scproject.scbef.pojo.expandenum.ImgTypeEnum;
import com.scproject.scbef.pojo.vo.ResponseCodeEnum;
import com.scproject.scbef.pojo.vo.SchoolNewsVo;
import com.scproject.scbef.service.study.schoolnews.SchoolNewsService;
import com.scproject.utils.FtpFileUtil;
import com.scproject.utils.JWTUtils;
import com.scproject.utils.ProcessFileUtils;
import com.scproject.utils.UUIDUtils;
import org.codehaus.plexus.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.scproject.utils.ProcessFileUtils.processFile;

/**
 * @author LNL
 * @date 2021/5/20 10:31
 */
@Service("schoolNewsService")
@Transactional
public class SchoolNewsServiceImpl implements SchoolNewsService {

    @Autowired
    private SchoolNewsInfoMapper schoolNewsInfoMapper;

    @Autowired
    private SchoolNewsMapper schoolNewsMapper;

    @Autowired
    private ImgRelationMapper imgRelationMapper;

    @Autowired
    private ImgMapper imgMapper;

    @Override
    public ResponseDto getAllSchoolNews() {
        ResponseDto responseDto = null;
        //[{},{},{}] :src="path" img
        List<SchoolNewsVo> datas = schoolNewsInfoMapper.getAllSchoolNews(ImgTypeEnum.SCHOOL_NEWS.toString());
        Optional<List<SchoolNewsVo>> optionalDatas = Optional.ofNullable(datas);
        if (optionalDatas.isPresent()) {
            responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(), "校园信息", datas);
        } else {
            responseDto = new ResponseDto(ResponseCodeEnum.ERROR.toString(), "获取数据失败，请联系管理员");
        }
        return responseDto;
    }

    @Override
    public ResponseDto deleteNewsById(String id) {
        //逻辑，删除了校园新闻之后，需要删除图片的关联
        ResponseDto responseDto = null;
        int isDelete = schoolNewsMapper.deleteByPrimaryKey(id);
        int isDeleteImgRe = imgRelationMapper.deleteByRelationId(id, ImgTypeEnum.SCHOOL_NEWS.toString());
        //删除id这条记录
        if (isDelete > 0 ) {
            responseDto = new ResponseDto("1000", "删除成功");
        } else {
            throw new ProcessException("删除失败,id无效,请重试");
        }
        return responseDto;
    }

    /* 增加校园新闻，所需要的字段
     * title、content、publishTime、imgPath
     * */
    @Override
    public ResponseDto insertNews(MultipartHttpServletRequest request) {
        ResponseDto responseDto = null;
        //处理文件,文件信息包含了fileName和filePath
        Map<String, String> fileInfo = null;
        try {
            //获取当前用户信息
            Map<String, String> userInfo = JWTUtils.getInfo(request.getHeader("token"));
            //处理时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //包含title、content、publishTime这三个信息
            Map<String, String[]> newsData = request.getParameterMap();
            //处理逻辑，如果数据不为空，那么创建校园新闻+图片关联
            SchoolNews schoolNews = new SchoolNews();
            schoolNews.setId(UUIDUtils.getUUID());
            schoolNews.setBrCount(0);
            schoolNews.setTitle(newsData.get("title")[0] == null ? "" : newsData.get("title")[0]);
            schoolNews.setContent(newsData.get("content")[0] == null ? "" : newsData.get("content")[0]);
            schoolNews.setPublishTime(
                    sdf.parse(newsData.get("publishTime")[0]) == null ?
                            new Date() :
                            sdf.parse(newsData.get("publishTime")[0]));
            schoolNews.setUserId(userInfo.get("userId"));
            schoolNews.setCreateUser(userInfo.get("userId"));
            schoolNews.setCreateTime(new Date());
            //对校园新闻进行新增
            int isInsertSchoolNews = schoolNewsMapper.insertSelective(schoolNews);
            if (isInsertSchoolNews > 0 ) {
                List<MultipartFile> files = request.getFiles("file_transfer");
                for (MultipartFile file : files) {
                    Map<String, String> fileData = ProcessFileUtils.processFile(file);
                    //将图片存放到数据库中
                    Img img = new Img();
                    img.setId(UUIDUtils.getUUID());
                    img.setName(fileData.get("fileName"));
                    img.setPath(fileData.get("filePath"));

                    ImgRelation imgRelation = new ImgRelation();
                    imgRelation.setId(UUIDUtils.getUUID());
                    imgRelation.setImgId(img.getId());
                    imgRelation.setRelationId(schoolNews.getId());
                    imgRelation.setType(ImgTypeEnum.SCHOOL_NEWS.toString());

                    //添加图片信息
                    int isInsertImg = imgMapper.insertSelective(img);
                    int isInsertImgRelation = imgRelationMapper.insertSelective(imgRelation);
                    if (isInsertImg > 0 && isInsertImgRelation > 0) {
                        responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(), "新增成功");
                    } else {
                        throw new ProcessException("添加失败");
                    }
                }
            } else {
                throw new ProcessException("新增失败,请联系管理员或重试");
            }
        } catch (Exception e) {
            throw new ProcessException("时间格式或字段异常，请联系管理员");
        }
        return responseDto;
    }

    /**
     * 修改校园信息
     * id、title、content、publishTime
     *
     * @return
     */
    @Override
    public ResponseDto updateSchoolNews(SchoolNews schoolNews, HttpServletRequest request) {
        ResponseDto responseDto = null;
        Map<String, String> userInfo = JWTUtils.getInfo(request.getHeader("token"));
        schoolNews.setEditUser(userInfo.get("userId"));
        schoolNews.setEditTime(new Date());

        //对新闻进行操作
        try {
            int isUpdate = schoolNewsMapper.updateByPrimaryKeySelective(schoolNews);
            if (isUpdate > 0) {
                responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(), "更新成功");
            } else {
                throw new ProcessException("更新失败");
            }
        } catch (Exception e) {
            throw new ProcessException("更新失败");
        }
        return responseDto;
    }


    public String insertImg(Map<String, String> fileInfo) {
        String tempId = "";
        //图片关联操作
        Img img = new Img();
        img.setId(UUIDUtils.getUUID());
        img.setPath(fileInfo.get("filePath"));
        img.setName(fileInfo.get("fileName"));
        //新增图片
        int count = imgMapper.insertSelective(img);
        if (count > 0) {
            tempId = img.getId();
        }
        return tempId;
    }

    public int insertImgRelation(String imgId, SchoolNews schoolNews) {
        //数据封装
        ImgRelation imgRelation = new ImgRelation();
        imgRelation.setId(UUIDUtils.getUUID());
        imgRelation.setRelationId(schoolNews.getId());
        imgRelation.setImgId(imgId);
        imgRelation.setType(ImgTypeEnum.SCHOOL_NEWS.toString());
        //新增图片关联
        int count = imgRelationMapper.insertSelective(imgRelation);
        return count;
    }

}
